﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.Linq;

namespace BIMP
{
    public class BIMPJobDefinition : SPJobDefinition
    {
        public BIMPJobDefinition()
        {
        }

        public BIMPJobDefinition(SPWebApplication webApp, RmdConfiguration config)
            : base(config.DisplayName, webApp, null, SPJobLockType.Job)
        {
            //this.LockType = SPJobLockType.Job;
            this.Title = string.Format("BIMP: {0} @{1}", config.DisplayName, DateTime.Now.ToString());

            Configuration = config;

            Schedule = config.Schedule;
        }

        public RmdConfiguration Configuration
        {
            get
            {
                RmdConfiguration ret = null;
                if (this.Properties.ContainsKey("BIMP"))
                {
                    string xml = Convert.ToString(this.Properties["BIMP"]);

                    ret = RmdConfiguration.ReadConfigurations(xml).FirstOrDefault();
                }
                return ret;
            }
            set
            {
                string serialized = RmdConfiguration.WriteConfigurations(new List<RmdConfiguration>() { value });
                this.Properties["BIMP"] = serialized;
            }
        }

        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);

            RmdConfiguration cfg = Configuration;

            NotificationEngine engine = new NotificationEngine(cfg);
            engine.SendEmails();
        }
    }
}
